package com.example.springbootlearn.controller;

import com.example.springbootlearn.service.impl.ParamService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author caiji Mr. Li
 * @date 2019/11/10 23:38
 */

@RequiredArgsConstructor
@RestController
public class TestController {

    private final ParamService paramService;
    ThreadLocal<String> threadLocal = new ThreadLocal<>();


    @GetMapping("/hello")
    public String test() {
        System.out.println("-----------" + Thread.currentThread().getName());
        System.out.println("hello");
        return "hello world！";
    }

    @GetMapping("/test")
    public String test(HttpServletRequest request) {
        System.out.println("-----------" + Thread.currentThread().getName());
        String token = request.getParameter("token");
        String s = threadLocal.get();
        if (s != null) {
            System.out.println("threadLocal中已经存储的值,token = " + s);
            return s;
        } else {
            threadLocal.set(token);
            System.out.println("请求参数中的token = " + token);
        }
        return token;
    }

    @GetMapping("/testSession")
    public String test(HttpSession httpSession, String token) {
        System.out.println("-----------" + Thread.currentThread().getName());

        Object tokenSession = httpSession.getAttribute("token");

        if (tokenSession != null) {
            System.out.println("tokenSession中已经存储的值,token = " + tokenSession);
            return tokenSession.toString();
        } else {
            httpSession.setAttribute("token", token);
            System.out.println("httpSession的token = " + token);
        }
        return token;
    }

    @GetMapping("/getParams")
    public String getParams() {
        System.out.println("-----------" + Thread.currentThread().getName());
        return paramService.getPhone();
    }

}
